package com.ckerchina.admin.ckadmin.utils;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Collection;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.fluent.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ShortUrlGenerator {

	private static Logger logger = LoggerFactory.getLogger(ShortUrlGenerator.class);

	public static void main(String[] args) {
		long t1 = System.currentTimeMillis();
		System.out.println(shortUrl("http://www.baijimu.com"));
		System.out.println(System.currentTimeMillis() - t1);
	}

	@SuppressWarnings("unchecked")
	public static String shortUrl(String longurl) {
		try {
			String url = "http://api.t.sina.com.cn/short_url/shorten.json?source=715879091&url_long="
					+ URLDecoder.decode(longurl, "UTF-8");
			String result = Request.Get(url).addHeader("Accept-Encoding", "gzip, deflate").socketTimeout(3000)
					.execute().handleResponse(new FluentUTF8ResponseHandler());
			Collection<Map<String, Object>> collection = JsonMapper.fromJson(result, Collection.class);
			if (collection != null && collection.size() > 0) {
				for (Map<String, Object> map : collection) {
					if (map.containsKey("url_short")) {
						String str = (String) map.get("url_short");
						if (StringUtils.isNotBlank(str)) {
							return str;
						}
					}
				}
			}
		} catch (ClientProtocolException e) {
			logger.error("请求新浪短地址失败", e);
		} catch (IOException e) {
			logger.error("请求新浪短地址失败", e);
		}
		return null;
	}
}